package com.ruoyi.equip.util;

import java.util.concurrent.*;

public class ExpiringMap<K, V> {
    private final ConcurrentHashMap<K, V> map = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<K, ScheduledFuture<?>> scheduledTasks = new ConcurrentHashMap<>();
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    public void put(K key, V value, long duration, TimeUnit unit) {
        map.put(key, value);

        // 取消之前的任务
        ScheduledFuture<?> previousTask = scheduledTasks.remove(key);
        if (previousTask != null) {
            previousTask.cancel(false);
        }

        // 添加新的任务
        ScheduledFuture<?> newTask = scheduler.schedule(() -> {
            map.remove(key);
            scheduledTasks.remove(key);
        }, duration, unit);

        scheduledTasks.put(key, newTask);
    }

    public V get(K key) {
        return map.get(key);
    }


}
